package dhee.wtqshopproject.utils;


import dhee.wtqshopproject.dao.OrderItemMapper;
import dhee.wtqshopproject.dao.OrderMapper;
import dhee.wtqshopproject.dao.ProductMapper;
import dhee.wtqshopproject.entity.*;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
public class OrderUtils {

    private static OrderUtils orderUtils;  // 静态实例

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;

    @PostConstruct
    public void init() {
        orderUtils = this;
        orderUtils.orderMapper = this.orderMapper;
    }

    // 通用用户登录校验
    private static void checkUserLogin() {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }
    }

    public static Integer createOrder(Order order) {
        checkUserLogin();

        // 生成唯一订单号（示例：时间戳 + 随机数）
        String orderNo = "ORD" +
                System.currentTimeMillis() +
                String.format("%06d", new Random().nextInt(999999));

        order.setOrderNo(orderNo); // 关键：设置订单号
        order.setUserId(UserContext.getCurrentUser().getUserId());
        order.setCreateTime(new Date());
        order.setStatus(0);

        orderUtils.orderMapper.createOrder(order);
        return order.getOrderId();
    }

    // 2. 获取用户所有订单
    public static List<Order> getUserOrders() {
        checkUserLogin();
        return orderUtils.orderMapper.selectByUserId(
                UserContext.getCurrentUser().getUserId()
        );
    }

    // 3. 删除订单（用户只能删除自己的订单）
    public static void deleteOrder(Integer orderId) {
        checkUserLogin();

        Order order = orderUtils.orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        orderUtils.orderMapper.deleteOrder(orderId);
    }

    // 4. 更新订单状态（管理员专用）
    public static void updateOrderStatus(Integer orderId, Integer status) {
        orderUtils.orderMapper.updateOrderStatus(orderId,status);
    }

    // 5. 获取订单详情（包含订单项）
    public static OrderDetail getOrderDetail(Integer orderId) {
        checkUserLogin();

        Order order = orderUtils.orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        return new OrderDetail(
                order,
                orderUtils.orderItemMapper.selectByOrderId(orderId)
        );
    }

    // 6. 后台获取全部订单
    public static List<Order> getAllOrders() {
        return orderUtils.orderMapper.selectAllOrders();
    }



    }
